package com.jobpass.realm;

import com.jobpass.common.model.Enterprise;
import com.jobpass.common.service.EnterpriseService;
import com.jobpass.shiro.salt.MyByteSource;
import com.jobpass.shiro.utils.ApplicationContextUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

public class UserRealm extends AuthorizingRealm {

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        //根据主身份信息获取角色 和权限信息
        EnterpriseService enterpriseServiceImpl = (EnterpriseService) ApplicationContextUtils.getBean("enterpriseServiceImpl");
        Enterprise enterprise = enterpriseServiceImpl.findRolesByUserName(primaryPrincipal);
        //授权角色信息
        if (!CollectionUtils.isEmpty(enterprise.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            enterprise.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
            });
            System.out.println ("执行了授权：doGetAuthorizationInfo");
            return simpleAuthorizationInfo;
        }
     return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken =(UsernamePasswordToken)token;
        EnterpriseService enterpriseServiceImpl = (EnterpriseService) ApplicationContextUtils.getBean("enterpriseServiceImpl");
        Enterprise enterprise = enterpriseServiceImpl.queryUserByName(userToken.getUsername());
        if (ObjectUtils.isEmpty(enterprise)){
            return  null;
        }
        System.out.println ("执行了认证：doGetAuthenticationInfo");
        return new SimpleAuthenticationInfo(enterprise.getAccount(),enterprise.getPassword(),new MyByteSource(enterprise.getSalt()),this.getName());
    }
}
